package org.snail.chat.service.chatchain.regular;

import lombok.NonNull;
import org.apache.log4j.Logger;
import org.snail.chat.service.chatchain.chain.ChatCreateOrUpdateHandler;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Chat创建更新规则链执行器
 */
public class HandlerManger {

    private static final Logger LOGGER =  Logger.getLogger(HandlerManger.class);

    public static Map<String, ChatCreateOrUpdateHandler> chatCreateOrUpdateHandlerMap;     //规则链

    /**
     * 获取规则链
     * @param regular
     * @return
     */
    public static ChatCreateOrUpdateHandler getChatCreateOrUpdateHandler(String regular){
        ChatCreateOrUpdateHandler chatCreateOrUpdateHandler = null;
        if(null!=chatCreateOrUpdateHandlerMap) {
            chatCreateOrUpdateHandler = chatCreateOrUpdateHandlerMap.get(regular);
        }
        return chatCreateOrUpdateHandler;
    }

    /**
     * 生成规则链
     * @param handlerRegularList  责任链列表
     */
    public static void generateChatCreateOrUpdateHandler(List<HandlerRegular> handlerRegularList){
        if(null!=handlerRegularList && !handlerRegularList.isEmpty()) {
            for (HandlerRegular oneHandlerRegular :  handlerRegularList) {
                generateChatCreateOrUpdateHandler(oneHandlerRegular);
            }
        }
    }

    /**
     * 生成规则链 并添加到Map中
     * @param handlerRegular
     * @return
     */
    public static void generateChatCreateOrUpdateHandler(HandlerRegular handlerRegular){

        if(null==chatCreateOrUpdateHandlerMap) {
            chatCreateOrUpdateHandlerMap = new HashMap<>();
        }
        Map<String,ChatCreateOrUpdateHandler> handlerRegularCreateOrUpdateHandlerMap = new HashMap<String, ChatCreateOrUpdateHandler>();
        if(null!=handlerRegular) {
           String lvRegular = handlerRegular.getLvRegular();
           String depIdRegular = handlerRegular.getDepIdRegular();

           //如果有lv按照lv生成规则，只有id规则时，按照id规则生成
           if(!StringUtils.isEmpty(lvRegular)) {
               handlerRegularCreateOrUpdateHandlerMap = generateLVRegularHandler(handlerRegular);
           } else if(!StringUtils.isEmpty(depIdRegular)) {
               handlerRegularCreateOrUpdateHandlerMap = generateDepIdListRegular(handlerRegular);
           }
            chatCreateOrUpdateHandlerMap.putAll(handlerRegularCreateOrUpdateHandlerMap);
        }
    }

    /**
     * id生成规则 为了生成map,需要设置depIdListRegular
     * @param handlerRegular
     * @return
     */
    private static Map<String,ChatCreateOrUpdateHandler> generateDepIdListRegular(HandlerRegular handlerRegular){
        Map<String,ChatCreateOrUpdateHandler> chatCreateOrUpdateHandlerMap = new HashMap<>();
        String depIdRegular = handlerRegular.getDepIdRegular();

        ChatCreateOrUpdateHandler chatCreateOrUpdateHandler = generateChatCreateOrUpdateHandlerRule(handlerRegular);
        if(null!=chatCreateOrUpdateHandler) {
            chatCreateOrUpdateHandlerMap.put(depIdRegular, chatCreateOrUpdateHandler);
        }
        return chatCreateOrUpdateHandlerMap;
    }

    /**
     * lv生成规则
     * @param handlerRegular
     * @return
     */
    private static Map<String,ChatCreateOrUpdateHandler> generateLVRegularHandler(HandlerRegular handlerRegular){
        Map<String,ChatCreateOrUpdateHandler> chatCreateOrUpdateHandlerMap = new HashMap<String,ChatCreateOrUpdateHandler>();
        String lvRegular = handlerRegular.getLvRegular();

        ChatCreateOrUpdateHandler chatCreateOrUpdateHandler = generateChatCreateOrUpdateHandlerRule(handlerRegular);
        if(null!=chatCreateOrUpdateHandler) {
            chatCreateOrUpdateHandlerMap.put(lvRegular, chatCreateOrUpdateHandler);
        }
        return chatCreateOrUpdateHandlerMap;
    }

    /**
     * 获取对应规则
     * @param handlerRegular 获取群组相应的规则
     * @return ChatCreateOrUpdateHandler 返回规则handler
     */
    private static ChatCreateOrUpdateHandler generateChatCreateOrUpdateHandlerRule(@NonNull HandlerRegular handlerRegular) {
        ChatCreateOrUpdateHandler chatCreateOrUpdateHandler = null;
        String regular = handlerRegular.getHandlerRegularRule();
        if(!StringUtils.isEmpty(regular)) {
            if (null != chatCreateOrUpdateHandlerMap && null != chatCreateOrUpdateHandlerMap.get(regular)) {
                chatCreateOrUpdateHandler = chatCreateOrUpdateHandlerMap.get(regular);
            } else {
                if (null == chatCreateOrUpdateHandlerMap) {
                    chatCreateOrUpdateHandlerMap = new HashMap<>();
                }

                //生成ChatCreateOrUpdateHandler责任链
                String[] regularArry = regular.split(",");
                ChatCreateOrUpdateHandler headChatCreateOrUpdateHandler = null;
                ChatCreateOrUpdateHandler preChatCreateOrUpdateHandler = null;
                for (int i = 0; i < regularArry.length; i++) {
                    String chatCreateOrUpdateHandlerKey = regularArry[i];

                    //实例化单个ChatCreateOrUpdateHandler
                    ChatCreateOrUpdateHandler oneChatCreateOrUpdateHandler = null;
                    if(!StringUtils.isEmpty(chatCreateOrUpdateHandlerKey)) {
                        oneChatCreateOrUpdateHandler = initOneChatCreateOrUpdateHandler(chatCreateOrUpdateHandlerKey);
                    }

                    if(null!=oneChatCreateOrUpdateHandler) {
                        oneChatCreateOrUpdateHandler.setHandlerRegular(handlerRegular);
                    }

                    //记录第一个Handler
                    if(null==preChatCreateOrUpdateHandler){
                        headChatCreateOrUpdateHandler = oneChatCreateOrUpdateHandler;
                    }

                    //责任链串起来
                    if(null!=preChatCreateOrUpdateHandler && null!=oneChatCreateOrUpdateHandler) {
                        preChatCreateOrUpdateHandler.setSuccessor(oneChatCreateOrUpdateHandler);
                    }
                    preChatCreateOrUpdateHandler=oneChatCreateOrUpdateHandler;
                }

                chatCreateOrUpdateHandler = headChatCreateOrUpdateHandler;
            }
        }
        return chatCreateOrUpdateHandler;
    }


    /**
     * 利用反射实例化对象
     * @param chatCreateOrUpdateHandlerKey
     * @return
     */
    private static ChatCreateOrUpdateHandler initOneChatCreateOrUpdateHandler(@NonNull String chatCreateOrUpdateHandlerKey){
        ChatCreateOrUpdateHandler chatCreateOrUpdateHandler = null;
        try {
            //需要获取到类的包名
            String packageName = "org.snail.chat.service.chatchain.chain" ;
            String urlName = packageName + "." + chatCreateOrUpdateHandlerKey;
            Class clazz = Class.forName(urlName);
            chatCreateOrUpdateHandler = (ChatCreateOrUpdateHandler)clazz.newInstance();
        } catch (Exception e) {
            LOGGER.error("根据对象名反射至对象失败！对象字符串：" + chatCreateOrUpdateHandlerKey, e);
        }
        return chatCreateOrUpdateHandler;
    }
}
